export function createStore(reducer, fn) {
  let state; // 用来存储哪些state
  let cb = [];
  function getState() {
    return JSON.parse(JSON.stringify(state))
  }
  function dispatch(action) {
    state = reducer(state, action)
    cb.forEach(f => {
      f()
    })
    console.log(state)
  }
  dispatch({ type: "@@types-qwsd345" })
  function subscribe(f) {
    cb.push(f);
    console.log(cb)
    return function () {
      cb = cb.filter(item => item !== f)
    }
  }
  if (typeof fn == 'function') {
    return fn(createStore)(reducer)
  }
  return {
    getState,
    dispatch,
    subscribe
  }
}
export function combineReducers(obj) {
  return function reducer(state, action) {
    state = state || {};
    // {count:{count:100},color:{color:'red'}}
    Object.keys(obj).forEach(key => {
      // key 就是我们的属性名
      state[key] = obj[key](state[key], action)
    })
    return state
  }
}

// export function applyMiddleware(middleWare) {
//   return function (createStore) {
//     return function (reducer) {
//       let store = createStore(reducer)
//       let temp1 = middleWare(store)
//       let newDispatch = temp1(store.dispatch)
//       return {
//         ...store,
//         dispatch: newDispatch
//       }
//     }
//   }
// }
function compose(...fns) {
  let last = fns.pop();
  return function c(...arg) {
    return fns.reduceRight((prev, next) => {
      return next(prev)
    }, last(...arg))
  }
}

export function applyMiddleware(...middleWares) {
  return function (createStore) {
    return function (reducer) {
      let store = createStore(reducer)
      let temp1s = middleWares.map(item => item(store))
      // temp1s = [f1,f2]
      let combinedTemp = compose(...temp1s)
      let newDispatch = combinedTemp(store.dispatch)
      return {
        ...store,
        dispatch: newDispatch
      }
    }
  }
}